package com.ynet.middleground.riskmanage.model.rizhaogang;

import java.time.LocalDateTime;
import java.util.*;

import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ynet.core.common.BaseReqObj;
import com.ynet.core.common.PagerInfo;
import com.ynet.core.exception.BusinessException;
import com.ynet.host.HostConstants;
import com.ynet.middleground.riskmanage.bean.newrizhaogang.NewRzgControlCargoAsynReq;
import com.ynet.middleground.riskmanage.bean.newrizhaogang.NewRzgControlCargoQueryReq;
import com.ynet.middleground.riskmanage.bean.newrizhaogang.NewRzgControlCargoReq;
import com.ynet.middleground.riskmanage.bean.newrizhaogang.NewRzgRegisterCustomerReq;
import com.ynet.middleground.riskmanage.bean.qdg.QdgAllGoodsInfoReq;
import com.ynet.middleground.riskmanage.bean.qdg.QdgOneGoodsInfoQueryReq;
import com.ynet.middleground.riskmanage.bean.qdg.QdgRegisterCustomerReq;
import com.ynet.middleground.riskmanage.bean.rizhaogang.*;
import com.ynet.middleground.riskmanage.bean.ytg.YtgControlCargoQueryReq;
import com.ynet.middleground.riskmanage.bean.ytg.YtgQueryTransferResultReq;
import com.ynet.middleground.riskmanage.common.SystemConstant;
import com.ynet.middleground.riskmanage.dao.*;
import com.ynet.middleground.riskmanage.dto.qdg.OneGoodsInfoDTO;
import com.ynet.middleground.riskmanage.dto.qdg.QdgAllGoodsInfoDTO;
import com.ynet.middleground.riskmanage.dto.qdg.QdgAllGoodsInfoDetailDTO;
import com.ynet.middleground.riskmanage.dto.qdg.QdgOneGoodsInfoDTO;
import com.ynet.middleground.riskmanage.dto.rizhaogang.*;
import com.ynet.middleground.riskmanage.dto.ytg.YtgTransferResultDTO;
import com.ynet.middleground.riskmanage.entity.QdgCustomer;
import com.ynet.middleground.riskmanage.entity.RzgCargoControlNew;
import com.ynet.middleground.riskmanage.entity.RzgCustomerNew;
import com.ynet.middleground.riskmanage.entity.qdg.QdgGoods;
import com.ynet.middleground.riskmanage.entity.rizhaogang.RzgNewGoods;
import com.ynet.middleground.riskmanage.entity.rizhaogang.RzgTransferCommandInfo;
import com.ynet.middleground.riskmanage.entity.ytg.YtgCargoControl;
import com.ynet.middleground.riskmanage.entity.ytg.YtgGoods;
import com.ynet.middleground.riskmanage.entity.ytg.YtgTransferCommandInfo;
import com.ynet.middleground.riskmanage.external.MainBusinessConfig;
import com.ynet.middleground.riskmanage.external.newrizhaogang.NewRzgApiHelper;
import com.ynet.middleground.riskmanage.external.newrizhaogang.NewRzgUriEnum;
import com.ynet.middleground.riskmanage.external.qcc.ApiHelper;
import com.ynet.middleground.riskmanage.external.qdg.QdgApiHelper;
import com.ynet.middleground.riskmanage.external.qdg.QdgUriEnum;
import com.ynet.middleground.riskmanage.external.rizhaogang.RzgApiHelper;
import com.ynet.middleground.riskmanage.external.ytg.YtgUriEnum;
import com.ynet.middleground.riskmanage.mq.producer.RzgCommandProducer;
import com.ynet.middleground.riskmanage.utils.ApiUtil;
import com.ynet.middleground.riskmanage.utils.BeanUtil;
import com.ynet.middleground.riskmanage.utils.DateUtils;
import com.ynet.middleground.riskmanage.utils.qdg.SignUtil;

/**
 * @ClassName NewRiZhaoGangModel
 * @Description 新日照港服务处理逻辑
 * @Author songyf
 * @Date 2022/05/12 14:32
 * @Version 1.0
 */
@Component
public class NewRiZhaoGangModel {
    @Autowired
    ApiUtil apiUtil;

    @Autowired
    ApiHelper apiHelper;

    @Autowired
    private RzgApiHelper rzgApiHelper;

    @Autowired
    private QdgApiHelper qdgApiHelper;

    @Autowired
    private RzgNewGoodsMapper rzgNewGoodsMapper;

    @Autowired
    private RzgTransferCommandMapper rzgTransferCommandMapper;

    @Autowired
    private Mapper mapper;
    @Autowired
    private DozerBeanMapper dozerBeanMapper;

    @Autowired
    private RzgCommandProducer rzgCommandProducer;

    @Autowired
    MainBusinessConfig mainBusinessConfig;

    @Autowired
    private RzgCustomerNewMapper rzgCustomerNewMapper;

    @Autowired
    private RzgCargoControlNewMapper rzgCargoControlNewMapper;

    @Autowired
    private YtgGoodsMapper ytgGoodsMapper;

    @Autowired
    private QdgGoodsMapper qdgGoodsMapper;

    @Autowired
    private YtgTransferCommandMapper ytgTransferCommandMapper;

    @Autowired
    private NewRzgApiHelper newRzgApiHelper;

    @Autowired
    private QdgCustomerMapper qdgCustomerMapper;

    @Autowired
    private YtgCargoControlMapper ytgCargoControlMapper;

    private static final String SUCCESS_FLAG = "S00001";

    public static final String LOG_NAME_YTG = "烟台港";

    public static final String TRANSFER_SUCCESS = "1003";
    public static final String TRANSFER_ERROR = "1004";

    /**
     * 日志打印时显示的名称
     */
    public static final String LOG_NAME = "新日照港";

    /**
     * 货物全量查询接口
     * 
     * @param req
     * @return
     */
    public List<RzgNewGoodsInfoDTO> queryAllGoods(RzgAllGoodsInfoQueryReq req) {
        if (StringUtils.isEmpty(req.getCustomerId()) || StringUtils.isEmpty(req.getFullName())) {
            throw new BusinessException("作业委托人ID和作业委托人名称必填", "ECRM0000");
        }
        // 请求信息
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", mainBusinessConfig.getRzgangSecret());
        Map<String, Object> params = new HashMap<>();
        params.put("id", req.getTraceId());
        params.put("lb", "货物全量数据查询");
        params.put("customerid", req.getCustomerId());
        params.put("fullname", req.getFullName());

        JSONObject apiResult = apiUtil.sendApiLog(NewRzgUriEnum.QUERY_ALL.getCode(),
            mainBusinessConfig.getRzgangNewUrl() + NewRzgUriEnum.QUERY_ALL.getUrl(), header, params,
            HostConstants.HTTP_METHOD_GET, LOG_NAME, req);
        String errorcode = apiResult.getString("errorcode");
        String errormsg = apiResult.getString("errormsg");
        String zywtr = apiResult.getString("zywtr");
        if (!StringUtils.isEmpty(errorcode)) {
            throw new BusinessException(errormsg, errorcode);
        }

        JSONArray datalists = apiResult.getJSONArray("datalists");
        // 传输对象
        List<RzgNewGoodsInfoDTO> rzgNewGoodsInfoDTOS = new ArrayList<>();
        rzgNewGoodsInfoDTOS = datalists.toJavaList(RzgNewGoodsInfoDTO.class);

        // 进行key值转换
        Map<String, String> map = new HashMap<>();
        map.put("shl", "dgshl");
        JSONArray result = BeanUtil.changeJsonArr(datalists, map);
        // 操作数据库对象
        List<RzgNewGoods> rzgNewGoods = new ArrayList<>();
        rzgNewGoods = result.toJavaList(RzgNewGoods.class);

        // 新增？修改？
        for (RzgNewGoods r : rzgNewGoods) {
            r.setSerialId(req.getTraceId());
            r.setChannel(req.getChannel());
            LambdaQueryWrapper<RzgNewGoods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RzgNewGoods::getCargokey, r.getCargokey());
            if (rzgNewGoodsMapper.selectCount(queryWrapper) > 0) {
                r.setModifiedBy(req.getOperationUserId());
                r.setGmtModified(LocalDateTime.now());
                rzgNewGoodsMapper.update(r, queryWrapper);
            } else {
                r.setCreateBy(req.getOperationUserId());
                r.setGmtCreate(LocalDateTime.now());
                rzgNewGoodsMapper.insert(r);
            }
        }
        // 多添加两个返回字段
        for (RzgNewGoodsInfoDTO r : rzgNewGoodsInfoDTOS) {
            r.setCommandId(req.getTraceId());
            r.setZywtr(zywtr);
        }
        return rzgNewGoodsInfoDTOS;
    }

    /**
     * 青岛港全量查询
     *
     * @param req
     * @return
     */
    public List<RzgNewGoodsInfoDTO> queryAllGoodsQDG(RzgAllGoodsInfoQueryReq req) {
        // 基础校验
        if (StringUtils.isEmpty(req.getCustomerId()) || StringUtils.isEmpty(req.getFullName())
            || StringUtils.isEmpty(req.getTerminalCode())) {
            throw new BusinessException("货代企业组织机构代码、货代企业全称、卸货港码头代码必填", "ECRM0000");
        }
        // 请求信息
        Map<String, String> reqInfo = new HashMap<String, String>();
        reqInfo.put("customerCode", mainBusinessConfig.getQdgCustomerCode());
        reqInfo.put("customerName", mainBusinessConfig.getQdgCustomerName());
        reqInfo.put("reqTime", DateUtils.getDateTime(new Date(), "yyyy-MM-dd HH:mm:ss"));
        // 业务参数 data
        QdgAllGoodsInfoReq data = new QdgAllGoodsInfoReq();
        data.setTerminalCode(req.getTerminalCode());
        data.setCargoCustomerCode(req.getCustomerId());
        data.setCargoCustomerName(req.getFullName());
        String strdata = JSON.toJSONString(data);
        reqInfo.put("data", strdata);
        String parStr = SignUtil.formatUrlMap(reqInfo, false, false);
        // 签名
        String sign = SignUtil.sign(parStr, mainBusinessConfig.getQdgPrivateKey(), "UTF-8");
        reqInfo.put("sign", sign);
        //
        Map<String, Object> objectMap = new HashMap<>(16);
        reqInfo.forEach((k, v) -> {
            objectMap.put(k, v);
        });

        JSONObject apiResult = qdgApiHelper.PostForm(QdgUriEnum.QUERY_GOODS_INFO.getCode(), req,
            mainBusinessConfig.getQdgUrl() + QdgUriEnum.QUERY_GOODS_INFO.getUrl(), null, objectMap);
        JSONObject resp = apiResult.getObject("resp", JSONObject.class);
        // code msg
        JSONObject message = resp.getObject("message", JSONObject.class);
        String code = message.getString("code");
        String msg = message.getString("msg");
        if (!"000".equals(code)) {
            throw new BusinessException(msg, code);
        }
        // 业务数据
        JSONObject cargoList = message.getObject("cargoList", JSONObject.class);
        // 传输对象
        QdgAllGoodsInfoDTO qdgAllGoodsInfoDTO = cargoList.toJavaObject(QdgAllGoodsInfoDTO.class);

        // 入库
        List<QdgAllGoodsInfoDetailDTO> cargoDescList = qdgAllGoodsInfoDTO.getCargoDescList();
        if (cargoDescList != null && cargoDescList.size() > 0) {
            for (QdgAllGoodsInfoDetailDTO d : cargoDescList) {
                QdgGoods qdgGoods = new QdgGoods();
                qdgGoods = dozerBeanMapper.map(d, QdgGoods.class);
                // 补充信息
                qdgGoods.setCargoCustomerName(qdgAllGoodsInfoDTO.getCargoCustomerName());
                qdgGoods.setCargoCustomerCode(qdgAllGoodsInfoDTO.getCargoCustomerCode());
                qdgGoods.setChannel(req.getChannel());
                // 新增||修改
                LambdaQueryWrapper<QdgGoods> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(QdgGoods::getCargoKey, qdgGoods.getCargoKey());
                if (qdgGoodsMapper.selectCount(queryWrapper) > 0) {
                    qdgGoods.setModifiedBy(req.getOperationUserId());
                    qdgGoods.setGmtModified(LocalDateTime.now());
                    qdgGoodsMapper.update(qdgGoods, queryWrapper);
                } else {
                    qdgGoods.setCreateBy(req.getOperationUserId());
                    qdgGoods.setGmtCreate(LocalDateTime.now());
                    qdgGoodsMapper.insert(qdgGoods);
                }
            }
        }

        // 整理返回
        List<RzgNewGoodsInfoDTO> rzgNewGoodsInfoDTOS = new ArrayList<>();
        RzgNewGoodsInfoDTO rzgNewGoodsInfoDTO = new RzgNewGoodsInfoDTO();
        rzgNewGoodsInfoDTO
            .setCargoInfo(StringUtils.isEmpty(qdgAllGoodsInfoDTO.getCargoCustomerCode()) ? null : qdgAllGoodsInfoDTO);
        rzgNewGoodsInfoDTOS.add(rzgNewGoodsInfoDTO);
        return rzgNewGoodsInfoDTOS;
    }

    /**
     * 查询货物信息-烟台港
     * 
     * @param req
     * @return
     */
    public List<RzgNewGoodsInfoDTO> queryAllGoodsYTG(RzgAllGoodsInfoQueryReq req, PagerInfo pagerInfo) {
        String tokenId = getTokenId(req);
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("clientNam", req.getFullName());
        requestBody.put("clientId", req.getCustomerId());
        requestBody.put("billNo", req.getHwdh());
        requestBody.put("sdbillCargoId", req.getCargokey());
        requestBody.put("rows", req.getRows());
        requestBody.put("page", req.getPage());
        // 请求信息
        Map<String, Object> requestRoot = getRequestInfo(tokenId, YtgUriEnum.QUERY_GOODS_INFO.getUrl(), requestBody);

        // 转调烟台港
        JSONObject apiResult = apiUtil.sendApiLog(YtgUriEnum.QUERY_GOODS_INFO.getCode(), mainBusinessConfig.getYtgUrl(),
            null, requestRoot, HostConstants.HTTP_METHOD_POST, LOG_NAME_YTG, req);

        // response root
        JSONObject responseRoot = apiResult.getJSONObject("responseRoot");
        // response header
        JSONObject responseHeader = responseRoot.getJSONObject("responseHeader");
        String resultCode = responseHeader.getString("resultCode");
        String resultDesc = responseHeader.getString("resultDesc");
        if (!SUCCESS_FLAG.equals(resultCode)) {
            throw new BusinessException(resultDesc, resultCode);
        }
        // response body
        JSONObject responseBody = responseRoot.getJSONObject("responseBody");
        JSONArray arrays = responseBody.getJSONArray("rows");
        Integer total = responseBody.getInteger("total");
        pagerInfo.setTotal(total);

        // 进行key值转换
        Map<String, String> changeMap = new HashMap<>();
        changeMap.put("SDBILL_CARGO_ID", "cargokey");
        changeMap.put("C_SHIP_NAM", "zhwchm");
        changeMap.put("E_SHIP_NAM", "ywcm");
        changeMap.put("VOYAGE", "hc");
        changeMap.put("CARGO_NAM", "hwmch");
        changeMap.put("FROM_PORT", "qyg");
        changeMap.put("TO_PORT_DTE", "dgrq");
        changeMap.put("AGENT_NAM", "dlgs");
        changeMap.put("BILL_WGT", "cdsl");
        changeMap.put("ORGN_NAM", "zygsmch");
        changeMap.put("SUB_ORGN_NAM", "zygsmch3");
        changeMap.put("CLIENT_ID", "zywtrid");
        changeMap.put("CLIENT_NAM", "zywtr");
        changeMap.put("BILL_NO", "hwdh");
        changeMap.put("SURPLUS_NUM", "sys");
        changeMap.put("FACT_OUT_WGT", "sjyfysl");
        changeMap.put("FACT_IN_WGT", "shl");
        changeMap.put("STORE_WGT", "kczl");
        JSONArray result = BeanUtil.changeJsonArr(arrays, changeMap);
        List<RzgNewGoodsInfoDTO> rzgNewGoods = result.toJavaList(RzgNewGoodsInfoDTO.class);
        // 新增？修改？
        for (RzgNewGoodsInfoDTO rzgNewGoodsInfoDTO : rzgNewGoods) {
            YtgGoods r = dozerBeanMapper.map(rzgNewGoodsInfoDTO, YtgGoods.class);
            r.setChannel(req.getChannel());
            r.setJgshl(rzgNewGoodsInfoDTO.getShl());
            LambdaQueryWrapper<YtgGoods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(YtgGoods::getCargokey, r.getCargokey());
            queryWrapper.eq(YtgGoods::getZywtrid, r.getZywtrid());
            if (ytgGoodsMapper.selectCount(queryWrapper) > 0) {
                r.setModifiedBy(req.getOperationUserId());
                r.setGmtModified(LocalDateTime.now());
                ytgGoodsMapper.update(r, queryWrapper);
            } else {
                r.setCreateBy(req.getOperationUserId());
                r.setGmtCreate(LocalDateTime.now());
                ytgGoodsMapper.insert(r);
            }
        }

        return rzgNewGoods;
    }

    /**
     * 货物非全量查询接口
     * 
     * @param req
     * @return
     */
    public List<RzgNewGoodsInfoDTO> queryPartGoods(RzgPartGoodsInfoQueryReq req) {
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", mainBusinessConfig.getRzgangSecret());
        Map<String, Object> params = new HashMap<>();
        params.put("id", req.getTraceId());
        params.put("lb", "货物非全量数据查询");
        params.put("customerid", req.getCustomerId());
        params.put("fullname", req.getFullName());
        params.put("hwmch", req.getHwmch());
        if (!StringUtils.isEmpty(req.getZhwchm())) {
            params.put("zhwchm", req.getZhwchm());
        }
        if (!StringUtils.isEmpty(req.getDgrqmm())) {
            params.put("dgrqmm", req.getDgrqmm());
        }
        if (!StringUtils.isEmpty(req.getHth())) {
            params.put("hth", req.getHth());
        }
        if (!StringUtils.isEmpty(req.getDw())) {
            params.put("dw", req.getDw());
        }
        JSONObject apiResult = apiUtil.sendApiLog(NewRzgUriEnum.QUERY_PART.getCode(),
            mainBusinessConfig.getRzgangNewUrl() + NewRzgUriEnum.QUERY_PART.getUrl(), header, params,
            HostConstants.HTTP_METHOD_GET, LOG_NAME, req);
        String errorcode = apiResult.getString("errorcode");
        String errormsg = apiResult.getString("errormsg");
        String zywtr = apiResult.getString("zywtr");
        if (!StringUtils.isEmpty(errorcode)) {
            throw new BusinessException(errormsg, errorcode);
        }

        JSONArray datalists = apiResult.getJSONArray("datalists");
        // 传输对象
        List<RzgNewGoodsInfoDTO> rzgNewGoodsInfoDTOS = new ArrayList<>();
        rzgNewGoodsInfoDTOS = datalists.toJavaList(RzgNewGoodsInfoDTO.class);

        // 进行key值转换
        Map<String, String> map = new HashMap<>();
        map.put("shl", "dgshl");
        JSONArray result = BeanUtil.changeJsonArr(datalists, map);
        // 操作数据库对象
        List<RzgNewGoods> rzgNewGoods = new ArrayList<>();
        rzgNewGoods = result.toJavaList(RzgNewGoods.class);

        // 新增？修改？
        for (RzgNewGoods r : rzgNewGoods) {
            r.setSerialId(req.getTraceId());
            r.setChannel(req.getChannel());
            LambdaQueryWrapper<RzgNewGoods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RzgNewGoods::getCargokey, r.getCargokey());
            if (rzgNewGoodsMapper.selectCount(queryWrapper) > 0) {
                r.setModifiedBy(req.getOperationUserId());
                r.setGmtModified(LocalDateTime.now());
                rzgNewGoodsMapper.update(r, queryWrapper);
            } else {
                r.setCreateBy(req.getOperationUserId());
                r.setGmtCreate(LocalDateTime.now());
                rzgNewGoodsMapper.insert(r);
            }
        }
        // 多添加两个返回字段
        for (RzgNewGoodsInfoDTO r : rzgNewGoodsInfoDTOS) {
            r.setCommandId(req.getTraceId());
            r.setZywtr(zywtr);
        }
        return rzgNewGoodsInfoDTOS;
    }

    /**
     * 货物单货键查询接口-日照港
     * 
     * @param req
     * @return
     */
    public List<OneGoodsInfoDTO> queryOneGoods(RzgOneGoodsInfoQueryReq req) {
        // 请求信息
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", mainBusinessConfig.getRzgangSecret());
        Map<String, Object> params = new HashMap<>();
        params.put("id", req.getTraceId());
        params.put("lb", "货物单货键数据查询");
        params.put("cargokey", req.getCargokey());
        JSONObject apiResult = apiUtil.sendApiLog(NewRzgUriEnum.QUERY_ONE.getCode(),
            mainBusinessConfig.getRzgangNewUrl() + NewRzgUriEnum.QUERY_ONE.getUrl(), header, params,
            HostConstants.HTTP_METHOD_GET, LOG_NAME, req);
        String errorcode = apiResult.getString("errorcode");
        String errormsg = apiResult.getString("errormsg");
        String zywtr = apiResult.getString("zywtr");
        if (!StringUtils.isEmpty(errorcode)) {
            throw new BusinessException(errormsg, errorcode);
        }

        JSONArray datalists = apiResult.getJSONArray("datalists");
        // 传输对象
        List<OneGoodsInfoDTO> rzgNewGoodsInfoDTOS = new ArrayList<>();
        rzgNewGoodsInfoDTOS = datalists.toJavaList(OneGoodsInfoDTO.class);

        // 进行key值转换
        Map<String, String> map = new HashMap<>();
        map.put("shl", "dgshl");
        JSONArray result = BeanUtil.changeJsonArr(datalists, map);
        // 操作数据库对象
        List<RzgNewGoods> rzgNewGoods = new ArrayList<>();
        rzgNewGoods = result.toJavaList(RzgNewGoods.class);

        // 新增？修改？
        for (RzgNewGoods r : rzgNewGoods) {
            r.setSerialId(req.getTraceId());
            r.setChannel(req.getChannel());
            LambdaQueryWrapper<RzgNewGoods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RzgNewGoods::getCargokey, r.getCargokey());
            if (rzgNewGoodsMapper.selectCount(queryWrapper) > 0) {
                r.setModifiedBy(req.getOperationUserId());
                r.setGmtModified(LocalDateTime.now());
                rzgNewGoodsMapper.update(r, queryWrapper);
            } else {
                r.setCreateBy(req.getOperationUserId());
                r.setGmtCreate(LocalDateTime.now());
                rzgNewGoodsMapper.insert(r);
            }
        }
        // 多添加两个返回字段
        for (OneGoodsInfoDTO r : rzgNewGoodsInfoDTOS) {
            r.setCommandId(req.getTraceId());
            r.setZywtr(zywtr);
        }
        return rzgNewGoodsInfoDTOS;
    }

    /**
     * 货物单货键查询接口-青岛港
     *
     * @param req
     * @return
     */
    public List<OneGoodsInfoDTO> queryOneGoodsQdg(RzgOneGoodsInfoQueryReq req) {
        // 请求信息
        Map<String, String> reqInfo = new HashMap<String, String>();
        reqInfo.put("customerCode", mainBusinessConfig.getQdgCustomerCode());
        reqInfo.put("customerName", mainBusinessConfig.getQdgCustomerName());
        reqInfo.put("reqTime", DateUtils.getDateTime(new Date(), "yyyy-MM-dd HH:mm:ss"));
        // 业务参数 data
        QdgOneGoodsInfoQueryReq data = new QdgOneGoodsInfoQueryReq();
        data.setCargokey(req.getCargokey());
        String strdata = JSON.toJSONString(data);
        reqInfo.put("data", strdata);
        String parStr = SignUtil.formatUrlMap(reqInfo, false, false);
        // 签名
        String sign = SignUtil.sign(parStr, mainBusinessConfig.getQdgPrivateKey(), "UTF-8");
        reqInfo.put("sign", sign);
        //
        Map<String, Object> objectMap = new HashMap<>(16);
        reqInfo.forEach((k, v) -> {
            objectMap.put(k, v);
        });

        JSONObject apiResult = qdgApiHelper.PostForm(QdgUriEnum.QUERY_ONE_GOODS_INFO.getCode(), req,
            mainBusinessConfig.getQdgUrl() + QdgUriEnum.QUERY_ONE_GOODS_INFO.getUrl(), null, objectMap);
        JSONObject resp = apiResult.getObject("resp", JSONObject.class);
        // code msg
        JSONObject message = resp.getObject("message", JSONObject.class);
        String code = message.getString("code");
        String msg = message.getString("msg");
        if (!"000".equals(code)) {
            throw new BusinessException(msg, code);
        }
        JSONObject cargoList = message.getJSONObject("cargoList");
        QdgOneGoodsInfoDTO qdgGoodsInfoDTOS = null;
        if (cargoList != null) {
            // 传输对象
            qdgGoodsInfoDTOS = cargoList.toJavaObject(QdgOneGoodsInfoDTO.class);

            // 入库
            QdgGoods qdgGoods = new QdgGoods();
            qdgGoods = dozerBeanMapper.map(qdgGoodsInfoDTOS, QdgGoods.class);
            // 新增||修改
            LambdaQueryWrapper<QdgGoods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(QdgGoods::getCargoKey, qdgGoods.getCargoKey());
            if (qdgGoodsMapper.selectCount(queryWrapper) > 0) {
                qdgGoods.setModifiedBy(req.getOperationUserId());
                qdgGoods.setGmtModified(LocalDateTime.now());
                qdgGoodsMapper.update(qdgGoods, queryWrapper);
            } else {
                qdgGoods.setCreateBy(req.getOperationUserId());
                qdgGoods.setGmtCreate(LocalDateTime.now());
                qdgGoods.setChannel(req.getChannel());
                qdgGoodsMapper.insert(qdgGoods);
            }
        }

        // 整理返回
        List<OneGoodsInfoDTO> oneGoodsInfoDTOS = new ArrayList<>();
        OneGoodsInfoDTO oneGoodsInfoDTO = new OneGoodsInfoDTO();
        oneGoodsInfoDTO.setCargoDetail(qdgGoodsInfoDTOS);
        oneGoodsInfoDTOS.add(oneGoodsInfoDTO);
        return oneGoodsInfoDTOS;
    }

    /**
     * 发起电子仓单转让指令
     * 
     * @param req
     * @return
     */
    public RzgTransferResultDTO dealTransferCommand(RzgTransferCommandReq req) {
        if (StringUtils.isEmpty(req.getHthin())) {
            throw new BusinessException("受让人(受让方)合同号不能为空", "ECRM0000");
        }
        if (StringUtils.isEmpty(req.getSrrhz())) {
            throw new BusinessException("受让人(受让方)货主不能为空", "ECRM0000");
        }
        if (StringUtils.isEmpty(req.getZhqbgfcdf())) {
            throw new BusinessException("转货前包干费承担方不能为空", "ECRM0000");
        }
        if (StringUtils.isEmpty(req.getZhhbgfcdf())) {
            throw new BusinessException("转货后库场使用费承担方不能为空", "ECRM0000");
        }
        if (StringUtils.isEmpty(req.getZhhkcsyfcdf())) {
            throw new BusinessException("转货后库场使用费承担方不能为空", "ECRM0000");
        }

        // 请求信息
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", mainBusinessConfig.getRzgangSecret());
        Map<String, Object> params = new HashMap<>();
        params.put("id", req.getTraceId());
        params.put("lb", "电子仓单转让指令");
        params.put("cargokey", req.getCargokey());
        params.put("zywtrid", req.getZywtrid());
        params.put("zywtr", req.getZywtr());
        params.put("crr", req.getCrr());
        params.put("hqcyr", req.getHqcyr());
        params.put("hthin", req.getHthin());
        params.put("srr", req.getSrr());
        params.put("srrhz", req.getSrrhz());
        params.put("cargokeyin", req.getCargokeyin());
        params.put("stackfrom", req.getStackfrom());
        params.put("stackto", req.getStackto());
        params.put("shl", req.getZhshl());
        params.put("zhrq", req.getZhrq());
        params.put("zhqbgfcdf", req.getZhqbgfcdf());
        params.put("zhhbgfcdf", req.getZhhbgfcdf());
        params.put("zhhkcsyfcdf", req.getZhhkcsyfcdf());
        params.values().removeIf(Objects::isNull);
        JSONObject apiResult = newRzgApiHelper.sendApiLog(NewRzgUriEnum.TRANSFER_COMMAND.getCode(),
            mainBusinessConfig.getRzgangNewUrl() + NewRzgUriEnum.TRANSFER_COMMAND.getUrl(), header, params,
            HostConstants.HTTP_METHOD_POST, LOG_NAME, req);
        // 进行key值转换
        Map<String, String> map = new HashMap<>();
        map.put("shl", "zhshl");
        apiResult = BeanUtil.changeJsonObj(apiResult, map);

        String errorcode = apiResult.getString("errorcode");
        String errormsg = apiResult.getString("errormsg");
        if (!StringUtils.isEmpty(errorcode)) {
            throw new BusinessException(errormsg, errorcode);
        }

        // 1003;1004;
        String data = apiResult.getString("data");
        String msg = null;
        if (TRANSFER_SUCCESS.equals(data)) {
            msg = "服务调用成功,指令异步处理中";
        }
        if (TRANSFER_ERROR.equals(data)) {
            msg = "服务调用失败";
        }
        // 将转让指令信息入库
        RzgTransferCommandInfo rzg = mapper.map(req, RzgTransferCommandInfo.class);
        rzg.setLb("电子仓单转让指令");
        rzg.setChannel(req.getChannel());
        rzg.setSerialId(req.getTraceId());
        rzg.setCreateBy(req.getOperationUserId());
        rzg.setGmtCreate(LocalDateTime.now());
        rzgTransferCommandMapper.insert(rzg);

        RzgTransferResultDTO rzgTransferResultDTO = new RzgTransferResultDTO();
        rzgTransferResultDTO.setCommandId(req.getTraceId());
        rzgTransferResultDTO.setCode(data);
        rzgTransferResultDTO.setMsg(msg);
        return rzgTransferResultDTO;
    }

    /**
     * 烟台港-发起电子仓单转让指令
     *
     * @param req
     * @return
     */
    public RzgTransferResultDTO dealYtgTransferCommand(RzgTransferCommandReq req) {
        if (StringUtils.isEmpty(req.getCrrid())) {
            throw new BusinessException("出让人(出让方)ID必填", "ECRM0000");
        }
        if (StringUtils.isEmpty(req.getSrrid())) {
            throw new BusinessException("受让人(受让方)ID必填", "ECRM0000");
        }
        if (StringUtils.isEmpty(req.getSrrmc())) {
            throw new BusinessException("受让人(受让方)名称必填", "ECRM0000");
        }
        if (StringUtils.isEmpty(req.getSrrzywtrid())) {
            throw new BusinessException("受让人(受让方)作业委托人ID必填", "ECRM0000");
        }

        LambdaQueryWrapper<YtgTransferCommandInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YtgTransferCommandInfo::getSerialId, req.getTraceId());
        if (ytgTransferCommandMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException("此指令已存在", "ECRM0000");
        }

        String tokenId = getTokenId(req);
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("SDBILL_ORDER_ID", req.getTraceId());
        requestBody.put("SDBILL_CARGO_ID", req.getCargokey());
        requestBody.put("ORDER_TYP", "2");
        requestBody.put("TRANSFEROR_ID", req.getCrrid());
        requestBody.put("TRANSFEROR_NAM", req.getCrr());
        requestBody.put("TRANSFEROR_CLIENT_ID", req.getZywtrid());
        requestBody.put("TRANSFEROR_CLIENT_NAM", req.getZywtr());
        requestBody.put("TRANSFEREE_ID", req.getSrrid());
        requestBody.put("TRANSFEREE_NAM", req.getSrrmc());
        requestBody.put("TRANSFEREE_CLIENT_ID", req.getSrrzywtrid());
        requestBody.put("TRANSFEREE_CLIENT_NAM", req.getSrr());
        requestBody.put("ORDER_WGT", req.getZhshl());
        requestBody.put("ORDER_DTE", req.getZhrq());
        requestBody.put("MARK_TXT", req.getRemark());

        // 请求信息
        Map<String, Object> requestRoot = getRequestInfo(tokenId, YtgUriEnum.TRANSFER_ORDER.getUrl(), requestBody);

        // 转调烟台港
        JSONObject apiResult = apiUtil.sendApiLog(YtgUriEnum.TRANSFER_ORDER.getCode(), mainBusinessConfig.getYtgUrl(),
            null, requestRoot, HostConstants.HTTP_METHOD_POST, LOG_NAME_YTG, req);

        // response root
        JSONObject responseRoot = apiResult.getJSONObject("responseRoot");
        // response header
        JSONObject responseHeader = responseRoot.getJSONObject("responseHeader");
        String resultCode = responseHeader.getString("resultCode");
        String resultDesc = responseHeader.getString("resultDesc");
        if (!SUCCESS_FLAG.equals(resultCode)) {
            throw new BusinessException(resultDesc, resultCode);
        }
        // 记录到数据库
        YtgTransferCommandInfo ytgTransferCommandInfo = dozerBeanMapper.map(req, YtgTransferCommandInfo.class);
        ytgTransferCommandInfo.setCreateBy(req.getOperationUserId());
        ytgTransferCommandInfo.setGmtCreate(LocalDateTime.now());
        ytgTransferCommandInfo.setSerialId(req.getTraceId());
        ytgTransferCommandInfo.setOperate("2");
        ytgTransferCommandMapper.insert(ytgTransferCommandInfo);
        // 返回信息
        RzgTransferResultDTO rzgTransferResultDTO = new RzgTransferResultDTO();
        rzgTransferResultDTO.setCommandId(req.getTraceId());
        rzgTransferResultDTO.setCode("1003");
        rzgTransferResultDTO.setMsg(resultDesc);
        return rzgTransferResultDTO;
    }

    /**
     * 接收电子仓单转让指令处理结果
     *
     * @param req
     * @return
     */
    public String receiveTransferResult(RzgReceiveTransferResultReq req) {
        // 将指令处理结果状态反写到指令信息表
        LambdaQueryWrapper<RzgTransferCommandInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RzgTransferCommandInfo::getSerialId, req.getOrderId());
        RzgTransferCommandInfo r = rzgTransferCommandMapper.selectOne(queryWrapper);
        if (r == null) {
            throw new BusinessException("该指令不存在:" + req.getOrderId(), "ECRM0000");
        }
        if (r != null) {
            if (!StringUtils.isEmpty(r.getStatus())) {
                throw new BusinessException("该指令已经处理过：" + req.getOrderId(), "ECRM0000");
            }
            r.setModifiedBy(req.getOperationUserId());
            r.setGmtModified(LocalDateTime.now());
            r.setStatus(req.getStatus());
            r.setProcTime(req.getProcTime());
            r.setErrorMsg(req.getErrorMsg());
            rzgTransferCommandMapper.update(r, queryWrapper);
        }

        // mq将指令结果推给渠道
        // Map<String, Object> data = new HashMap<>();
        // data.put("traceId", req.getTraceId());
        // data.put("requestTime", req.getRequestTime());
        // data.put("orderId", req.getTraceId());
        // data.put("procTime", req.getProcTime());
        // data.put("status", req.getStatus());
        // data.put("errorMsg", req.getErrorMsg());
        // rzgCommandProducer.sendMessagesCustomerAnalytics(data);
        return "success";

    }

    /*
    注册用户信息
     */
    public String registerCustomer(NewRzgRegisterCustomerReq req) {
        // 青岛港
        if ("1".equals(req.getChanType())) {
            if (req.getQdgRegisterCustomerReq() == null) {
                throw new BusinessException("企业信息同步请求信息（青岛港专用）不能为空", "ECRM0000");
            }
            if (!"新增".equals(req.getQdgRegisterCustomerReq().getCargoAgentType())
                && !"更名".equals(req.getQdgRegisterCustomerReq().getCargoAgentType())) {
                throw new BusinessException("客户类型错误：" + req.getQdgRegisterCustomerReq().getCargoAgentType(),
                    "ECRM0000");
            }
            // 请求信息
            Map<String, String> reqInfo = new HashMap<String, String>();
            reqInfo.put("customerCode", mainBusinessConfig.getQdgCustomerCode());
            reqInfo.put("customerName", mainBusinessConfig.getQdgCustomerName());
            reqInfo.put("reqTime", DateUtils.getDateTime(new Date(), "yyyy-MM-dd HH:mm:ss"));
            // 业务参数 data
            String strdata = JSON.toJSONString(req.getQdgRegisterCustomerReq());
            reqInfo.put("data", strdata);
            String parStr = SignUtil.formatUrlMap(reqInfo, false, false);
            // 签名
            String sign = SignUtil.sign(parStr, mainBusinessConfig.getQdgPrivateKey(), "UTF-8");
            reqInfo.put("sign", sign);
            //
            Map<String, Object> objectMap = new HashMap<>(16);
            reqInfo.forEach((k, v) -> {
                objectMap.put(k, v);
            });
            JSONObject apiResult = qdgApiHelper.PostForm(QdgUriEnum.REGISTER_GOODS_INFO.getCode(), req,
                mainBusinessConfig.getQdgUrl() + QdgUriEnum.REGISTER_GOODS_INFO.getUrl(), null, objectMap);
            // JSONObject apiResult = JSONObject.parseObject("{\n" + "\t\"success\": true,\n" + "\t\"message\": {\n"
            // + "\t\t\"code\": \"000\",\n" + "\t\t\"msg\": \"成功\",\n" + "\t\t\"cargoList\": []\n" + "\t}\n" + "}");
            JSONObject resp = apiResult.getObject("resp", JSONObject.class);
            JSONObject message = resp.getObject("message", JSONObject.class);
            String code = message.getString("code");
            String msg = message.getString("msg");
            if (!"000".equals(code)) {
                throw new BusinessException(msg, code);
            }
            // 入库
            QdgRegisterCustomerReq reqCustomer = req.getQdgRegisterCustomerReq();
            QdgCustomer qdgCustomer = dozerBeanMapper.map(reqCustomer, QdgCustomer.class);
            if ("新增".equals(reqCustomer.getCargoAgentType())) {
                LambdaQueryWrapper<QdgCustomer> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(QdgCustomer::getCargoAgentCode, reqCustomer.getCargoAgentCode());
                if (qdgCustomerMapper.selectCount(queryWrapper) > 0) {
                    throw new BusinessException("客户已存在：" + reqCustomer.getCargoAgentCode(), "ECRM0000");
                }
                qdgCustomer.setGmtCreate(LocalDateTime.now());
                qdgCustomer.setCreateBy(req.getOperationUserId());
                qdgCustomer.setChannel(req.getChannel());
                qdgCustomerMapper.insert(qdgCustomer);
            } else {
                LambdaQueryWrapper<QdgCustomer> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(QdgCustomer::getCargoAgentCode, reqCustomer.getCargoAgentCode());
                if (qdgCustomerMapper.selectCount(queryWrapper) == 0) {
                    throw new BusinessException("客户不存在：" + reqCustomer.getCargoAgentCode(), "ECRM0000");
                }
                qdgCustomer.setGmtModified(LocalDateTime.now());
                qdgCustomer.setModifiedBy(req.getOperationUserId());
                queryWrapper.eq(QdgCustomer::getCargoAgentCode, reqCustomer.getCargoAgentCode());
                qdgCustomerMapper.update(qdgCustomer, queryWrapper);
            }

        }
        // 日照港
        if ("0".equals(req.getChanType())) {
            if (StringUtils.isEmpty(req.getCzhjgdm())) {
                throw new BusinessException("组织机构代码不能为空", "ECRM0000");
            }
            if (StringUtils.isEmpty(req.getCustomerid())) {
                throw new BusinessException("客户id不能为空", "ECRM0000");
            }
            if (StringUtils.isEmpty(req.getFullname())) {
                throw new BusinessException("客户全称不能为空", "ECRM0000");
            }
            if (StringUtils.isEmpty(req.getUrl())) {
                throw new BusinessException("用户授权协议链接地址不能为空", "ECRM0000");
            }
            if (StringUtils.isEmpty(req.getType())) {
                throw new BusinessException("客户类型不能为空", "ECRM0000");
            }
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", mainBusinessConfig.getRzgangSecret());
            Map<String, Object> params = new HashMap<>();
            params.put("id", req.getTraceId());
            params.put("lb", "注册用户信息");
            params.put("czhjgdm", req.getCzhjgdm());
            params.put("customerid", req.getCustomerid());
            params.put("fullname", req.getFullname());
            params.put("url", req.getUrl());
            params.put("type", req.getType());
            if (StringUtils.isNotBlank(req.getCustomeridold())) {
                params.put("customeridold", req.getCustomeridold());
            }
            if (StringUtils.isNotBlank(req.getFullnameold())) {
                params.put("fullnameold", req.getFullnameold());
            }
            JSONObject apiResult = newRzgApiHelper.sendApiLog(NewRzgUriEnum.REGISTER_CUSTOMER.getCode(),
                mainBusinessConfig.getRzgangNewUrl() + NewRzgUriEnum.REGISTER_CUSTOMER.getUrl(), header, params,
                HostConstants.HTTP_METHOD_POST, LOG_NAME, req);
            String data = apiResult.getString("data");
            if ("fail".equals(data)) {
                String errorcode = apiResult.getString("errorcode");
                String errormsg = apiResult.getString("errormsg");
                throw new BusinessException(errormsg, errorcode);
            }
            RzgCustomerNew rzgCustoms = dozerBeanMapper.map(req, RzgCustomerNew.class);
            rzgCustoms.setId(req.getTraceId());
            rzgCustoms.setLb("注册用户信息");
            if ("新增".equals(req.getType())) {
                rzgCustoms.setGmtCreate(LocalDateTime.now());
                rzgCustoms.setCreateBy(req.getOperationUserId());
                rzgCustomerNewMapper.insert(rzgCustoms);
            } else if ("更名".equals(req.getType())) {
                rzgCustoms.setGmtModified(LocalDateTime.now());
                rzgCustoms.setModifiedBy(req.getOperationUserId());
                LambdaQueryWrapper<RzgCustomerNew> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(RzgCustomerNew::getCustomerid, req.getCustomeridold());
                queryWrapper.eq(RzgCustomerNew::getFullname, req.getFullnameold());
                rzgCustomerNewMapper.update(rzgCustoms, queryWrapper);
            }
        }
        String returnsResult = SystemConstant.SYSTEM_SUCCESS;
        return returnsResult;
    }

    /*
    控货(解除)指令接收服务
     */
    public NewRzgCargoControlResultDTO controlCargo(NewRzgControlCargoReq req) {
        NewRzgCargoControlResultDTO returnsResult = new NewRzgCargoControlResultDTO();
        if ("0".equals(req.getChanType())) {
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", mainBusinessConfig.getRzgangSecret());
            Map<String, Object> params = new HashMap<>();
            params.put("id", req.getTraceId());
            params.put("cargokey", req.getCargokey());
            params.put("shl", req.getShl());
            if ("0".equals(req.getOperate())) {
                params.put("lb", "控货指令接收");
            } else if ("1".equals(req.getOperate())) {
                if (StringUtils.isBlank(req.getCtrlid())) {
                    throw new BusinessException("解除控货时控货指令id不能为空", "ECRM0000");
                }
                params.put("lb", "控货解除指令接收");
                params.put("ctrlid", req.getCtrlid());
            }
            JSONObject apiResult = newRzgApiHelper.sendApiLog(NewRzgUriEnum.CARGO_CONTROL.getCode(),
                mainBusinessConfig.getRzgangNewUrl() + NewRzgUriEnum.CARGO_CONTROL.getUrl(), header, params,
                HostConstants.HTTP_METHOD_POST, LOG_NAME, req);
            String data = apiResult.getString("data");
            RzgCargoControlNew cargoControl = mapper.map(req, RzgCargoControlNew.class);
            cargoControl.setCreateBy(req.getOperationUserId());
            cargoControl.setGmtCreate(LocalDateTime.now());
            cargoControl.setModifiedBy(req.getOperationUserId());
            cargoControl.setGmtModified(LocalDateTime.now());
            cargoControl.setShul(req.getShl());
            cargoControl.setId(req.getTraceId());
            if ("0".equals(req.getOperate())) {
                cargoControl.setLb("控货指令接收");
            } else if ("1".equals(req.getOperate())) {
                cargoControl.setLb("控货解除指令接收");
            }
            if ("1004".equals(data)) {
                String errorcode = apiResult.getString("errorcode");
                String errormsg = apiResult.getString("errormsg");
                throw new BusinessException(errormsg, errorcode);
            }
            String code = apiResult.getString("data");
            returnsResult.setCode(code);
            if ("1001".equals(code)) {
                returnsResult.setMsg("服务调用成功，指令同步处理成功");
            } else if ("1002".equals(code)) {
                returnsResult.setMsg("服务调用成功，指令同步处理失败");
                // String errormsg = apiResult.getString("errormsg");
                // cargoControl.setErrorMsg(errormsg);
                // cargoControl.setStatus(code);
            } else if ("1003".equals(code)) {
                returnsResult.setMsg("服务调用成功，指令异步处理中");
            } else if ("1004".equals(code)) {
                returnsResult.setMsg("服务调用失败");
            }
            cargoControl.setStatus(code);
            rzgCargoControlNewMapper.insert(cargoControl);
        } else if ("2".equals(req.getChanType())) {
            if (StringUtils.isBlank(req.getCzri())) {
                throw new BusinessException("操作日期不可为空", "ECRM0003");
            }
            if (StringUtils.isBlank(req.getCustomerId())) {
                throw new BusinessException("作业委托人ID不可为空", "ECRM0003");
            }
            if (StringUtils.isBlank(req.getFullName())) {
                throw new BusinessException("作业委托人全称不可为空", "ECRM0003");
            }
            String tokenId = getTokenId(req);
            Map<String, String> header = new HashMap<>();
            Map<String, Object> params = new HashMap<>();
            params.put("SDBILL_ORDER_ID", req.getTraceId());
            params.put("SDBILL_CARGO_ID", req.getCargokey());
            params.put("SDBILL_CLIENT_ID", req.getCustomerId());
            params.put("SDBILL_CLIENT_NAM", req.getFullName());
            params.put("ORDER_WGT", req.getShl());
            params.put("ORDER_TYP", req.getOperate());
            params.put("ORDER_DTE", req.getCzri());
            params.put("MARK_TXT", req.getRemark());
            // 请求信息
            Map<String, Object> requestRoot = getRequestInfo(tokenId, YtgUriEnum.CARGO_CONTROL.getUrl(), params);

            // 转调烟台港
            JSONObject apiResult = apiUtil.sendApiLog(YtgUriEnum.CARGO_CONTROL.getCode(),
                mainBusinessConfig.getYtgUrl(), null, requestRoot, HostConstants.HTTP_METHOD_POST, LOG_NAME_YTG, req);
            // JSONObject apiResult = newRzgApiHelper.sendApiLog(NewRzgUriEnum.CARGO_CONTROL.getCode(),
            // mainBusinessConfig.getRzgangNewUrl() + NewRzgUriEnum.CARGO_CONTROL.getUrl(), header, params,
            // HostConstants.HTTP_METHOD_POST, LOG_NAME, req);
            // JSONObject apiResult = JSONObject.parseObject(apiResultString);

            // response root
            JSONObject responseRoot = apiResult.getJSONObject("responseRoot");
            // response header
            JSONObject responseHeader = responseRoot.getJSONObject("responseHeader");

            String resultCode = responseHeader.getString("resultCode");
            String resultDesc = responseHeader.getString("resultDesc");
            if (!SUCCESS_FLAG.equals(resultCode)) {
                throw new BusinessException(resultDesc, resultCode);
            }
            // response body
            // JSONObject responseBody = responseRoot.getJSONObject("responseBody");
            String status = responseRoot.getString("responseBody");
            returnsResult.setCode(status);
            returnsResult.setMsg(resultDesc);
            // String msg = responseBody.getString("msg");
            YtgCargoControl cargoControl = mapper.map(req, YtgCargoControl.class);
            cargoControl.setCreateBy(req.getOperationUserId());
            cargoControl.setGmtCreate(LocalDateTime.now());
            cargoControl.setModifiedBy(req.getOperationUserId());
            cargoControl.setGmtModified(LocalDateTime.now());
            cargoControl.setShul(req.getShl());
            cargoControl.setSerialId(req.getTraceId());
            // cargoControl.setStatus(status);
            // cargoControl.setMsg(msg);
            ytgCargoControlMapper.insert(cargoControl);
        }
        returnsResult.setCommandId(req.getTraceId());
        return returnsResult;
    }

    /*
    控货指令接收查询服务--日照港
     */
    public NewRzgCargoControlQueryResultDTO controlCargoQuery(NewRzgControlCargoQueryReq req) {
        NewRzgCargoControlQueryResultDTO returnsResult = new NewRzgCargoControlQueryResultDTO();
        if ("0".equals(req.getChanType())) {
            if (StringUtils.isBlank(req.getCtrlid())) {
                throw new BusinessException("指令ID不能为空", "ECCT0000");
            }
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", mainBusinessConfig.getRzgangSecret());
            Map<String, Object> params = new HashMap<>();
            params.put("id", req.getTraceId());
            params.put("lb", "控货指令接收查询");
            params.put("ctrlid", req.getCtrlid());
            JSONObject apiResult = apiUtil.sendApiLog(NewRzgUriEnum.CARGO_CONTROL_QUERY.getCode(),
                mainBusinessConfig.getRzgangNewUrl() + NewRzgUriEnum.CARGO_CONTROL_QUERY.getUrl(), header, params,
                HostConstants.HTTP_METHOD_GET, LOG_NAME, req);
            String data = apiResult.getString("data");
            if ("1005".equals(data)) {
                String errorcode = apiResult.getString("errorcode");
                String errormsg = apiResult.getString("errormsg");
                throw new BusinessException(errormsg, errorcode);
            }
            String code = apiResult.getString("data");
            returnsResult.setCode(code);
            if ("1001".equals(code)) {
                returnsResult.setMsg("未接收");
            } else if ("1002".equals(code)) {
                returnsResult.setMsg("已接收未处理");
            } else if ("1003".equals(code)) {
                returnsResult.setMsg("已接收已处理(通过)");
            } else if ("1004".equals(code)) {
                returnsResult.setMsg("已接收已处理(未通过)");
            } else if ("1005".equals(code)) {
                returnsResult.setMsg("服务调用失败");
            }
        }
        return returnsResult;
    }

    /*
    控货指令接收查询服务--烟台港
     */
    public List<YtgCargoControlQueryResultDTO> controlCargoQueryYtg(YtgControlCargoQueryReq req) {
        List<YtgCargoControlQueryResultDTO> returnsResults = new ArrayList<>();
        if ("2".equals(req.getChanType())) {
            // if (StringUtils.isBlank(req.getCtrlid()) && StringUtils.isBlank(req.getCargokey())) {
            // throw new BusinessException("指令ID和在港货物ID至少上送一个", "ECCT0000");
            // }
            // LambdaQueryWrapper<YtgCargoControl> queryWrapper = new LambdaQueryWrapper<>();
            // queryWrapper.eq(YtgCargoControl::getSerialId, req.getCtrlid());
            // if (ytgCargoControlMapper.selectCount(queryWrapper) == 0) {
            // throw new BusinessException("此指令不存在", "ECRM0000");
            // }
            String tokenId = getTokenId(req);
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("orderId", req.getCtrlid());
            requestBody.put("cargoId", req.getCargokey());
            requestBody.put("rows", req.getPagerInfo().getPageSize());
            requestBody.put("page", req.getPagerInfo().getPageNum());
            // 请求信息
            Map<String, Object> requestRoot =
                getRequestInfo(tokenId, YtgUriEnum.QUERY_CARGO_CONTROL.getUrl(), requestBody);

            // 转调烟台港
            JSONObject apiResult = apiUtil.sendApiLog(YtgUriEnum.QUERY_CARGO_CONTROL.getCode(),
                mainBusinessConfig.getYtgUrl(), null, requestRoot, HostConstants.HTTP_METHOD_POST, LOG_NAME_YTG, req);
            // response root
            JSONObject responseRoot = apiResult.getJSONObject("responseRoot");
            // response header
            JSONObject responseHeader = responseRoot.getJSONObject("responseHeader");

            String resultCode = responseHeader.getString("resultCode");
            String resultDesc = responseHeader.getString("resultDesc");
            if (!SUCCESS_FLAG.equals(resultCode)) {
                throw new BusinessException(resultDesc, resultCode);
            }
            // response body
            JSONObject responseBody = responseRoot.getJSONObject("responseBody");
            // 进行key值转换
            Map<String, String> changeMap = new HashMap<>();
            changeMap.put("SDBILL_ORDER_ID", "ctrlid");
            changeMap.put("SDBILL_CARGO_ID", "cargokey");
            changeMap.put("ORDER_TYP", "orderType");
            changeMap.put("PERFORM_TIM", "freezeTime");
            changeMap.put("PERFORM_MARK_TXT", "remark");
            changeMap.put("ORDER_STATUS", "state");
            changeMap.put("ORDER_STATUS_TXT", "msg");
            JSONArray result = BeanUtil.changeJsonArr(responseBody.getJSONArray("rows"), changeMap);
            returnsResults = result.toJavaList(YtgCargoControlQueryResultDTO.class);
            req.getPagerInfo().setTotal(Integer.valueOf(responseBody.getString("total")));
            // 将状态信息 更新到数据库
            for (YtgCargoControlQueryResultDTO resultDTO : returnsResults) {
                LambdaQueryWrapper<YtgCargoControl> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(YtgCargoControl::getSerialId, resultDTO.getCtrlid());
                queryWrapper.orderByDesc(YtgCargoControl::getGmtModified);
                List<YtgCargoControl> ytgCargoControlLists = ytgCargoControlMapper.selectList(queryWrapper);
                if (ytgCargoControlLists.size() > 0) {
                    YtgCargoControl ytgCargoControl = ytgCargoControlLists.get(0);
                    ytgCargoControl.setStatus(resultDTO.getState());
                    ytgCargoControl.setMsg(resultDTO.getMsg());
                    ytgCargoControl.setModifiedBy(req.getOperationUserId());
                    ytgCargoControl.setGmtModified(LocalDateTime.now());
                    ytgCargoControlMapper.updateById(ytgCargoControl);
                }
            }
        }
        return returnsResults;
    }

    /*
        控货结果异步通知(日照港向金控中台推送控货结果数据)
     */
    public String controlCargoAsyn(NewRzgControlCargoAsynReq req) {
        // 将指令处理结果状态反写到指令信息表
        LambdaQueryWrapper<RzgCargoControlNew> queryWrapper = new LambdaQueryWrapper<>();
        if ("0".equals(req.getOrderType())) {
            queryWrapper.eq(RzgCargoControlNew::getId, req.getOrderId());
        } else if ("1".equals(req.getOrderType())) {
            queryWrapper.eq(RzgCargoControlNew::getId, req.getRelieveOrderId());
        }
        RzgCargoControlNew r = rzgCargoControlNewMapper.selectOne(queryWrapper);
        if (r == null) {
            throw new BusinessException("该指令不存在", "ECRM0000");
        }
        if (StringUtils.isNotBlank(r.getProcTime())) {
            throw new BusinessException("该指令已经处理过:" + r.getId(), "ECRM0000");
        }
        r.setModifiedBy(req.getOperationUserId());
        r.setGmtModified(LocalDateTime.now());
        r.setStatus(req.getStatus());
        r.setProcTime(req.getProcTime());
        r.setErrorMsg(req.getErrorMsg());
        rzgCargoControlNewMapper.update(r, queryWrapper);

        // mq将指令结果推给渠道
        // Map<String, Object> data = new HashMap<>();
        // data.put("traceId",req.getTraceId());
        // data.put("requestTime",req.getRequestTime());
        // data.put("orderId",req.getOrderId());
        // data.put("relieveOrderId",req.getRelieveOrderId());
        // data.put("orderType",req.getOrderType());
        // data.put("procTime",req.getProcTime());
        // data.put("status",req.getStatus());
        // data.put("errorMsg",req.getErrorMsg());
        // rzgCommandProducer.sendJkztfkToDzcdKhjgzt(data);
        String returnsResult = SystemConstant.SYSTEM_SUCCESS;
        return returnsResult;
    }

    /**
     * 烟台港-查询转让指令结果
     * 
     * @param req
     * @return
     */
    public List<YtgTransferResultDTO> queryTransferResult(YtgQueryTransferResultReq req) {
        /*if (StringUtils.isEmpty(req.getTransferid()) && StringUtils.isEmpty(req.getCargokey())) {
            throw new BusinessException("转让指令ID和在港货物ID至少上送一个", "ECCT0000");
        }*/
        String tokenId = getTokenId(req);
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("orderId", req.getTransferid());
        requestBody.put("cargoId", req.getCargokey());
        requestBody.put("rows", req.getPagerInfo().getPageSize());
        requestBody.put("page", req.getPagerInfo().getPageNum());
        // 请求信息
        Map<String, Object> requestRoot =
            getRequestInfo(tokenId, YtgUriEnum.QUERY_TRANSFER_RESULT.getUrl(), requestBody);

        // 转调烟台港
        JSONObject apiResult = apiUtil.sendApiLog(YtgUriEnum.QUERY_TRANSFER_RESULT.getCode(),
            mainBusinessConfig.getYtgUrl(), null, requestRoot, HostConstants.HTTP_METHOD_POST, LOG_NAME_YTG, req);

        // response root
        JSONObject responseRoot = apiResult.getJSONObject("responseRoot");
        // response header
        JSONObject responseHeader = responseRoot.getJSONObject("responseHeader");
        String resultCode = responseHeader.getString("resultCode");
        String resultDesc = responseHeader.getString("resultDesc");
        if (!SUCCESS_FLAG.equals(resultCode)) {
            throw new BusinessException(resultDesc, resultCode);
        }
        // response body
        JSONObject responseBody = responseRoot.getJSONObject("responseBody");
        JSONArray arrays = responseBody.getJSONArray("rows");
        Integer total = responseBody.getInteger("total");

        // 进行key值转换
        Map<String, String> changeMap = new HashMap<>();
        changeMap.put("SDBILL_ORDER_ID", "transferid");
        changeMap.put("SDBILL_CARGO_ID", "cargokey");
        changeMap.put("PERFORM_TIM", "cdzrsj");
        changeMap.put("PERFORM_MARK_TXT", "remark");
        changeMap.put("ORDER_STATUS", "zt");
        changeMap.put("ORDER_STATUS_TXT", "ztsm");
        JSONArray result = BeanUtil.changeJsonArr(arrays, changeMap);
        List<YtgTransferResultDTO> resultDTOs = result.toJavaList(YtgTransferResultDTO.class);
        if (resultDTOs != null && resultDTOs.size() > 0) {
            for (YtgTransferResultDTO y : resultDTOs) {
                // 将状态信息 更新到数据库
                LambdaQueryWrapper<YtgTransferCommandInfo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(YtgTransferCommandInfo::getSerialId, y.getTransferid());
                YtgTransferCommandInfo ytgTransferCommandInfo = ytgTransferCommandMapper.selectOne(queryWrapper);

                if (ytgTransferCommandInfo != null) {
                    ytgTransferCommandInfo.setStatus(y.getZt());
                    ytgTransferCommandInfo.setMsg(y.getZtsm());
                    ytgTransferCommandInfo.setModifiedBy(req.getOperationUserId());
                    ytgTransferCommandInfo.setGmtModified(LocalDateTime.now());
                    ytgTransferCommandMapper.updateById(ytgTransferCommandInfo);
                }
            }
        }
        req.getPagerInfo().setTotal(total);
        return resultDTOs;
    }

    /**
     * 烟台港-获取tokenID
     *
     * @param req
     * @return
     */
    public String getTokenId(BaseReqObj req) {
        // requestBody信息
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("sendCode", mainBusinessConfig.getSendCode());
        requestBody.put("secretKey", mainBusinessConfig.getSecretKey());
        // 请求信息
        Map<String, Object> requestRoot = getRequestInfo("", YtgUriEnum.GET_TOKEN.getUrl(), requestBody);
        // 转调烟台港
        JSONObject apiResult = apiUtil.sendApiLog(YtgUriEnum.GET_TOKEN.getCode(), mainBusinessConfig.getYtgUrl(), null,
            requestRoot, HostConstants.HTTP_METHOD_POST, LOG_NAME_YTG, req);

        // mock数据 响应信息
        // String apiResultString =
        // "{\n" + "\t\"responseRoot\": {\n" + "\t\t\"responseHeader\": {\n" + "\t\t\t\"resultCode\": \"S00001\",\n"
        // + "\t\t\t\"resultDesc\": \"调用成功\",\n" + "\t\t\t\"timestamp\": \"1520845026332\"\n" + "\t\t},\n"
        // + "\t\t\"responseBody\": {\"tokenId\":\"C8A739E5F9CF0200E053AC1010543D79\"}\n" + "\t}\n" + "}\n";
        // JSONObject apiResult = JSONObject.parseObject(apiResultString);

        // response root
        JSONObject responseRoot = apiResult.getJSONObject("responseRoot");
        // response header
        JSONObject responseHeader = responseRoot.getJSONObject("responseHeader");
        // response body
        JSONObject responseBody = responseRoot.getJSONObject("responseBody");

        String resultCode = responseHeader.getString("resultCode");
        String resultDesc = responseHeader.getString("resultDesc");
        if (!SUCCESS_FLAG.equals(resultCode)) {
            throw new BusinessException(resultDesc, resultCode);
        }
        String tokenId = responseBody.getString("tokenId");
        return tokenId;
    }

    /**
     * 烟台港-封装请求信息
     *
     * @param tokenId
     * @param methodCode
     * @param requestBody
     * @return
     */
    public Map<String, Object> getRequestInfo(String tokenId, String methodCode, Map<String, Object> requestBody) {
        // header部分
        Map<String, Object> requestHeader = new HashMap<>();
        requestHeader.put("tokenId", tokenId);
        requestHeader.put("messageId", UUID.randomUUID());
        requestHeader.put("timestamp", System.currentTimeMillis());
        requestHeader.put("methodCode", methodCode);
        // 和requestBody拼成requestRoot
        Map<String, Object> requestRoot = new HashMap<>();
        requestRoot.put("requestHeader", requestHeader);
        requestRoot.put("requestBody", requestBody);
        // 返回root
        Map<String, Object> root = new HashMap<>();
        root.put("requestRoot", requestRoot);
        return root;
    }
}
